<script setup lang="ts">
import { onMounted, ref, onBeforeMount, computed } from 'vue'
import {
	addUserService,
	deleteUserService,
	getUserByUserInfoService,
	getUserService,
	updateUserService
} from '../../api/user'
import { getClassnameListService } from '@/api/education/classname'
import { TUser } from '../../Types/user'
import avatar from '../../assets/Images/MIUI03.jpg'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '../../router'
import { standardDateTime } from '../../Tools/Time/date'
import { Search } from '@element-plus/icons-vue'
import AddUserByDialog from './components/user/addUserByDialog.vue'
import AddUserListDialog from '@/views/Backend/components/user/addUserListDialog.vue'
import EditUserDialog from './components/user/editUserDialog.vue'
import { uploadFileService, getFileSpecificService } from '../../api/file'
import { baseURL } from '../../utils/request'

// 初始化
const loading = ref(true)
const user_data = ref<TUser[]>([])
// 添加用户类型相关变量
const currentUserType = ref<number | null>(null)
const userTypes = [
	{ id: 1, name: '学生' },
	{ id: 2, name: '老师' },
	{ id: 3, name: '辅导员' },
	{ id: 4, name: '管理员' }
]

// 测试数据
// const testData = [
// 	{
// 		userId: 1,
// 		avatar: avatar,
// 		userType: '测试数据',
// 		createTime: '测试数据',
// 		reviseTime: '测试数据'
// 	}
// ]
// user_data.value = testData

/**
 * 分页器
 */
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
// 分页处理方法
const handleSizeChange = (val: number) => {
	pageSize.value = val
	getUser()
}
// 当前页
const handleCurrentChange = (val: number) => {
	currentPage.value = val
	getUser()
}

/**
 * 修改用户状态
 */
const columnloading = ref(false)
let statusUpdateTimer: NodeJS.Timeout | null = null // 添加定时器
const handleStatusChange = async (row: TUser) => {
	columnloading.value = true

	// 如果存在之前的定时器，清除它
	if (statusUpdateTimer) {
		clearTimeout(statusUpdateTimer)
	}

	// 设置新的定时器
	statusUpdateTimer = setTimeout(async () => {
		const data = {
			userId: row.userId,
			enable: row.enable === true ? 1 : 0
		}

		const res = await updateUserService(data)
		if (res.data.code === 1) {
			ElMessage.success('状态更新成功')
		} else {
			row.enable = !row.enable // 取反
			ElMessage.error('状态更新失败')
		}
		columnloading.value = false
	}, 500) // 0.5s 的延迟
}

/**
 * 添加用户
 */
const addUserDialogRef = ref()
// 打开添加用户对话框
const dialogAddUserVisible = ref(false)
const openAddUserDialog = () => {
	dialogAddUserVisible.value = true
}
// 关闭添加用户对话框
const closeAddUserDialog = (data: boolean) => {
	// console.log(data)
	dialogAddUserVisible.value = data
}
// 获取输入的表单数据，添加用户
const addUser = async (data: { userData: TUser; fileData: FormData }) => {
	try {
		// 初始化状态
		addUserDialogRef.value.openUserDialogLoading()

		// 添加用户核心逻辑
		const res = await addUserService(data.userData)
		if (res.data.code !== 1) {
			ElMessage.error('用户添加失败')
			return // 提前返回，不执行后续逻辑
		}

		ElMessage.success('用户添加成功')

		// 文件上传逻辑封装
		const uploadAvatar = async () => {
			if (![...data.fileData.values()].some((v) => v instanceof File)) return

			delete data.userData.classId
			const userRes = await getUserByUserInfoService(data.userData)

			if (userRes.data.code === 1 && userRes.data.data.length > 0) {
				const newUserId = userRes.data.data[0].userId
				// console.log('新用户ID:', newUserId)
				data.fileData.append('userId', String(newUserId))

				const uploadRes = await uploadFileService(data.fileData)
				if (uploadRes.data.code === 1) {
					ElMessage.success('头像上传成功')
					// console.log('头像上传成功，响应:', uploadRes.data)
				} else {
					ElMessage.error('头像上传失败')
				}
			} else {
				// console.error('获取新用户信息失败:', userRes.data)
			}
		}

		await uploadAvatar()
		// 重新获取用户列表以显示新用户的头像
		await getUser()
	} catch (error) {
		// console.error('添加用户失败:', error)
		ElMessage.error('操作过程中发生异常')
	} finally {
		// 统一状态重置
		addUserDialogRef.value.clearFormData()
		addUserDialogRef.value.closeUserDialogLoading()
		loading.value = false
		dialogAddUserVisible.value = false
	}
}

/**
 * 批量添加用户
 */
const dialogAddUserListVisible = ref(false)
const openAddUserListDialog = () => {
	dialogAddUserListVisible.value = true
}
const closeAddUserListDialog = (data: boolean) => {
	dialogAddUserListVisible.value = false
	// 仅在添加成功时刷新用户列表
	if (data === true) {
		getUser()
	}
}

/**
 * 编辑用户
 */
const dialogEditUserVisible = ref(false)
const currentEditUser = ref<TUser>({})
const editUserDialogRef = ref()

// 打开编辑用户对话框
const openEditUserDialog = (user: TUser) => {
	currentEditUser.value = { ...user }
	dialogEditUserVisible.value = true
}

// 关闭编辑用户对话框
const closeEditUserDialog = (data: boolean) => {
	dialogEditUserVisible.value = data
}

// 更新用户信息
const updateUser = async (userData: TUser) => {
	// console.log(userData)
	const params = {
		classId: userData.classIdList,
		...userData
	}

	try {
		const res = await updateUserService(params)
		if (res.data.code === 1) {
			ElMessage.success('用户信息更新成功')
		} else {
			ElMessage.error('用户信息更新失败')
		}
		dialogEditUserVisible.value = false
		await getUser()
	} catch (error) {
		console.error('更新用户失败:', error)
		ElMessage.error('更新用户过程中发生异常')
	}
}

// 删除指定id的用户
const deleteById = async (userId: number) => {
	// console.log(userId)
	ElMessageBox.confirm('确定删除该用户吗?', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning'
	})
		//确认
		.then(async () => {
			const res = await deleteUserService(userId)
			if (res.data.code === 1) {
				ElMessage.success('删除成功')

				await getUser()
			} else {
				ElMessage.error('删除失败')
			}
		})
		//取消
		.catch(() => {
			ElMessage.info('取消删除')
		})
}

// 查看用户详情
const lookById = (userId: number) => {
	// console.log(userId)

	router.push(`/userInfo/${userId}`)
}

/**
 * 数据处理
 */

// 处理数据
const userInfoChange = computed(() => {
	return user_data.value.map((item) => ({
		...item,
		enable: item.enable === 1 ? true : false
	}))
})
// 修改获取用户数据的计算属性
const userData = computed(() => {
	const processedData = userInfoChange.value
	if (currentUserType.value === null) {
		return processedData
	}
	return processedData.filter((user) => user.userTypeId === currentUserType.value)
})
// 添加用户类型切换方法
const handleUserTypeChange = (typeId: number | null) => {
	currentUserType.value = typeId
}

/**
 * 获取用户头像
 */
const getUserAvatar = async (avatarId?: number) => {
	if (!avatarId) {
		// console.log('头像ID为空')
		return null
	}

	try {
		// console.log('正在获取头像, ID:', avatarId)
		const res = await getFileSpecificService({ id: avatarId, fileType: 'avatar' })
		// console.log('头像API响应:', res.data)

		if (res.data.code === 1 && res.data.data && res.data.data.length > 0) {
			const url = baseURL + '/public/uploads/' + res.data.data[0].fileName
			// console.log('构建头像URL:', url)
			return url
		} else {
			// console.log('头像API响应无效数据')
		}
	} catch (error) {
		// console.error('获取头像失败:', error)
	}

	return null
}

/**
 * 数据获取
 */

// 获取全部用户
const getUser = async () => {
	loading.value = true

	try {
		const res = await getUserService({
			currentPage: currentPage.value,
			pageSize: pageSize.value
		})
		// console.log(res.data.data)
		user_data.value = res.data.data.list

		// 获取所有用户的头像
		for (const user of user_data.value) {
			if (user.avatarId) {
				// console.log('处理用户头像:', user.userId, '头像ID:', user.avatarId)
				const avatarUrl = await getUserAvatar(user.avatarId)
				if (avatarUrl) {
					user.avatar = avatarUrl
				}
			} else {
				// console.log('用户没有头像ID:', user.userId)
			}
		}

		total.value = res.data.data.total
	} catch (error) {
		console.error('获取用户数据出错:', error)
		ElMessage.error('获取用户数据失败')
	} finally {
		loading.value = false
	}
}
// 钩子
onMounted(() => {
	getUser()
})
</script>

<template>
	<div class="user-manage-container">
		<div class="header">
			<div class="breadcrumb">
				<el-breadcrumb separator="/">
					<el-breadcrumb-item @click="handleUserTypeChange(null)">全部用户</el-breadcrumb-item>
					<el-breadcrumb-item v-if="currentUserType !== null">{{
						userTypes.find((t) => t.id === currentUserType)?.name
					}}</el-breadcrumb-item>
				</el-breadcrumb>
			</div>
			<div class="action-container">
				<el-select
					v-model="currentUserType"
					clearable
					placeholder="筛选用户"
					@clear="handleUserTypeChange(null)"
				>
					<el-option v-for="type in userTypes" :key="type.id" :label="type.name" :value="type.id" />
				</el-select>
				<!-- <el-input style="width: 180px" placeholder="相关数据" :suffix-icon="Search" /> -->
				<el-button type="primary" @click="openAddUserDialog">添加</el-button>
				<el-button type="primary" @click="openAddUserListDialog">批量添加</el-button>
			</div>
		</div>

		<div class="table-container">
			<el-table :data="userData" v-loading="loading" height="100%" style="width: 100%">
				<el-table-column type="index" label="序号" width="100"></el-table-column>
				<el-table-column prop="uname" label="姓名" width="100"></el-table-column>
				<el-table-column prop="avatar" label="头像" width="200px">
					<template #default="scope">
						<el-image
							:src="scope.row.avatar ? scope.row.avatar : avatar"
							:preview-src-list="[scope.row.avatar ? scope.row.avatar : avatar]"
							:initial-index="0"
							fit="cover"
							style="height: 100px; width: 100px"
						></el-image>
					</template>
				</el-table-column>
				<el-table-column prop="userTypeId" label="类型" width="100">
					<template #default="{ row }">
						<el-tag v-if="row.userTypeId === 1" type="info">学生</el-tag>
						<el-tag v-else-if="row.userTypeId === 2" type="success">老师</el-tag>
						<el-tag v-else-if="row.userTypeId === 3" type="warning">辅导员</el-tag>
						<el-tag v-else-if="row.userTypeId === 4" type="danger">管理员</el-tag>
						<el-tag v-else type="info">未知</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="注册时间" width="210">
					<template #default="{ row }">{{ standardDateTime(row.createTime) }}</template>
				</el-table-column>
				<!-- <el-table-column prop="reviseTime" label="修改时间" width="230"></el-table-column> -->
				<el-table-column prop="enable" label="状态" width="80">
					<template #default="{ row }">
						<div v-loading="columnloading">
							<el-switch v-model="row.enable" @change="handleStatusChange(row)" />
						</div>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="200" fixed="right">
					<template #default="scope">
						<el-button type="primary" size="small" @click="lookById(scope.row.userId)"
							>查看</el-button
						>
						<el-button type="warning" size="small" @click="openEditUserDialog(scope.row)"
							>编辑</el-button
						>
						<el-button type="danger" size="small" @click="deleteById(scope.row.userId)"
							>删除</el-button
						>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<div class="footer">
			<el-pagination
				v-model:current-page="currentPage"
				v-model:page-size="pageSize"
				:page-sizes="[10, 20, 30, 50]"
				:background="true"
				layout="total, sizes, prev, pager, next"
				:total="total"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			/>
		</div>

		<!-- 对话框 -->
		<AddUserByDialog
			ref="addUserDialogRef"
			:dialogVisible="dialogAddUserVisible"
			@closeDialog="closeAddUserDialog"
			@setUserData="addUser"
		/>

		<AddUserListDialog
			v-model:dialogVisible="dialogAddUserListVisible"
			@closeDialog="closeAddUserListDialog"
		/>

		<EditUserDialog
			ref="editUserDialogRef"
			:dialogVisible="dialogEditUserVisible"
			:userData="currentEditUser"
			@closeDialog="closeEditUserDialog"
			@updateUser="updateUser"
		/>
	</div>
</template>

<style lang="scss" scoped>
.user-manage-container {
	height: 84vh;
	display: flex;
	flex-direction: column;
	padding: 20px;
	box-sizing: border-box;
	overflow: hidden;
}

.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20px;
	flex-shrink: 0;
	.action-container {
		display: flex;
		// margin-left: 10px;
		gap: 16px;
		align-items: center;
		.el-select {
			width: 100px;
		}
	}
}

.breadcrumb :deep(.el-breadcrumb__item) {
	cursor: pointer;
}

.table-container {
	flex: 1;
	min-height: 0;
	overflow: hidden;
}

.footer {
	margin-top: 20px;
	display: flex;
	justify-content: flex-end;
	flex-shrink: 0;
}

/* 解决el-image和el-table的冲突 */
:deep(.el-table__cell) {
	position: static;
}
</style>
